package com.itheima.health.service.impl;

import com.itheima.health.dao.PermissionDao;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.dao.UserDao;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.PermissionService;
import com.itheima.health.service.RoleService;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhangmeng
 * @description 用户服务实现类
 * @date 2019/9/6
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private RoleDao roleDao;
    /*
    修改findByUsername方法,让其返回值中有权限字段
     */
    @Override
    public User findByUsername(String username) {
        User user = userDao.selectByUsername(username);
        if(user==null){
            return null;
        }
        //查找权限关键字
        //先通过用户名,获取当前用户id
        Integer userId = user.getId();//userId 用户id
        //通过用户id获取该用户有哪些角色
        List<Role> roleList = roleDao.getAllRole(userId);   //roleList:所有角色
            //遍历
        for (Role oneRole : roleList) {//oneRole:一个角色
            //根据一个角色,得到该角色的id
            Integer roleId = oneRole.getId();//roleId:一个角色的id
            //根据该角色id查到所有权限
            List<Permission> permissionList = permissionDao.getAllPermission(roleId);
            oneRole.getPermissions().addAll(permissionList);//将查到的数据通过Role实体类,封装到permissions属性
        }
        user.getRoles().addAll(roleList);//现在,角色表中,已经有权限信息,将角色信息封装到User实体类中
        return user;
    }
}
